package cn.josh.daolmpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.josh.bean.Ec_shopcar;
import cn.josh.dao.Ec_shopcarDao;
import cn.josh.utill.JDBCUtil;

public class Ec_shopcarDaoImpl implements Ec_shopcarDao 
{
	public int insertShop(Ec_shopcar shopcar)
	{
		//先查询用户的购物车是否已经有该商品
		String sql = "SELECT * FROM ec_shopcar WHERE articleId=? AND userid = ?;";
		String[] info = {shopcar.getArticleId(),shopcar.getUserId()};
		ResultSet rs = JDBCUtil.executeQuery(sql, info);
		
		try 
		{
			if(rs.next())
			{
				//有则增加
				sql = "UPDATE ec_shopcar SET buyNum = buyNum+? WHERE userId=? AND articleId = ?;";
				String[] infoPlus = {shopcar.getBuyNum(),shopcar.getUserId(),shopcar.getArticleId()};
				int in = JDBCUtil.executeUpdate(sql, infoPlus);
				return in;
			}
			else
			{
				//无则新增
				sql = "INSERT INTO ec_shopcar (articleId,buyNum,userId) VALUE (?,?,?); ";
				String[] infoAdd = {shopcar.getArticleId(),shopcar.getBuyNum(),shopcar.getUserId()};
				int in = JDBCUtil.executeUpdate(sql, infoAdd);
				return in;
			}
		} 
		catch (SQLException e) 
		{
			
			e.printStackTrace();
		}
		return 0;
	}
	
	public List<Ec_shopcar> findCarList(String userId) 
	{
		String sql = "SELECT  b.`ID`,b.`IMAGE`,b.`TITLE`,b.`PRICE`,b.`DISCOUNT`,a.`buyNum`,a.`userId`,a.`articleId` "
				+ "FROM  ec_shopcar a INNER JOIN ec_article b ON a.`articleId`=b.`ID` WHERE a.`userId`= ?;";
		String[] info = {userId};
		List<Ec_shopcar> list = new ArrayList<Ec_shopcar>();
		ResultSet rs = JDBCUtil.executeQuery(sql, info);
		
		try 
		{
			while(rs.next())
			{
				Ec_shopcar shopList = new Ec_shopcar();
				shopList.setId(rs.getString("id"));
				shopList.setImage(rs.getString("image"));
				shopList.setTitle(rs.getString("title"));
				shopList.setPrice(rs.getString("price"));
				shopList.setDiscount(rs.getString("discount"));
				shopList.setBuyNum(rs.getString("buyNum"));
				shopList.setUserId(rs.getString("userId"));
				shopList.setArticleId(rs.getString("articleId"));
				
				System.out.println(shopList);
				list.add(shopList);
			}
		} 
		catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return list;
	}


	public int deleteShop(Ec_shopcar shopcar) 
	{
		String sql = "DELETE FROM ec_shopcar WHERE userId = ? AND articleId = ?;";
		String[] info = {shopcar.getUserId(),shopcar.getArticleId()};
		System.out.println("Ec_shopcarDaoImpl 将要删除的商品id是：" + shopcar.getArticleId());
		System.out.println("用户id是：" + shopcar.getUserId());
		int in = JDBCUtil.executeUpdate(sql, info);
		return in;
	}

}
